package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.QxMapMapper;
import com.xxl.job.executor.dao.QxRainfallMapper;
import com.xxl.job.executor.model.QxRainfall;
import com.xxl.job.executor.utils.CmUtil;
import com.xxl.job.executor.utils.ConstUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;

/*
        "各区市降雨量抓取"
 */

public class RainFallTask {
    private static Logger logger = LoggerFactory.getLogger(RainFallTask.class);


    private String taskContents;
    @Autowired
    private ConstUtil constUtil;

    private QxRainfallMapper qxRainfallMapper;

    @XxlJob(value = "RainFallTask",init = "init", destroy = "destroy")
    public ReturnT<String> RainFallTask(String param) throws Exception {
//        if (constUtil == null) {
//            constUtil = SpringContextHolder.getBean(ConstUtil.class);
//        }
//        if (qxRainfallMapper == null) {
//            qxRainfallMapper = SpringContextHolder.getBean(QxRainfallMapper.class);
//        }
        //  String indexUrl = "http://123.234.44.227:8080/indexnew.jsp";
        // 修改 解引用null返回值
        Document document = getHtml(constUtil.rainIndexUrl, constUtil);
        if (document == null) {
            System.out.println("空了");
        };
        String nextUrl = document.select("[style=width:400px;vertical-align:top;]")
                .select("iframe").attr("SRC");
        String sinceTime = nextUrl.substring(21,37);
        String endTime = nextUrl.substring(45,61);
        // 数据SRC
        // String URL = "http://123.234.44.227:8080/"+nextUrl;
        String URL = constUtil.rainIndexUrl.substring(0, constUtil.rainIndexUrl.lastIndexOf("/") + 1) + nextUrl;
        Document doc = getHtml(URL, constUtil);
        if (doc == null) {
            System.out.println("kong");
        };
        Elements tdEle = doc.select("td");
        for (int i=2;i<tdEle.size()-2;i++){
            QxRainfall qxRainfall;
            try{
                // 获取区市名称
                String dist = tdEle.get(i).text();
                // 获取过去24小时降雨量
                String rainfall = tdEle.get(i+1).text();
                i++;
                // 获取日期
                String createdDate = CmUtil.date2day(null);
                ArrayList<String> rainfallList = new ArrayList<>();
                rainfallList.add(rainfall);
                // 根据日期和地区查询当天的降雨量数据是否存在
                qxRainfall = qxRainfallMapper.selectByDateAndDist(createdDate,dist);
                if(qxRainfall==null){
                    // 不存在，插入一条新数据
                    try {
                        qxRainfall = new QxRainfall();
                        qxRainfall.setQxRainfallId(CmUtil.getUUID());
                        qxRainfall.setCreatedDate(CmUtil.date2day(null));
                        qxRainfall.setUrbanDistrictName(dist);
                        qxRainfall.setAverageRainfall(rainfall);
                        qxRainfall.setSinceTime(sinceTime);
                        qxRainfall.setEndTime(endTime);
                        // 存入数据库
                        qxRainfallMapper.insertSelective(qxRainfall);
                        this.taskContents = "插入"+dist+" "+createdDate+" "+"平均降雨量数据成功！";
                    }catch (Exception e){
                        e.printStackTrace();
                        this.taskContents = "插入"+dist+" "+createdDate+" "+"平均降雨量数据异常！";
                    }

                }else if(!qxRainfall.getAverageRainfall().equals(rainfallList.get(0))){
                    // 更新已有数据
                    try{
                        qxRainfall.setAverageRainfall(rainfall);
                        qxRainfall.setSinceTime(sinceTime);
                        qxRainfall.setEndTime(endTime);
                        // 更新数据库
                        qxRainfallMapper.updateByPrimaryKeySelective(qxRainfall);
                        this.taskContents = "更新"+dist+" "+createdDate+" "+"平均降雨量数据成功！";
                    }catch (Exception e){
                        e.printStackTrace();
                        this.taskContents = "更新"+dist+" "+createdDate+" "+"平均降雨量数据异常！";
                    }
                }else{
                    qxRainfall.setSinceTime(sinceTime);
                    qxRainfall.setEndTime(endTime);
                    qxRainfallMapper.updateByPrimaryKeySelective(qxRainfall);
                }
                this.taskContents = "降雨量数据获取成功！";
            }catch (Exception e){
                e.printStackTrace();
                this.taskContents = "降雨量数据获取异常！";
            }
        }

        return ReturnT.SUCCESS;
    }

    /**
     * 获取HTML内容
     *
     * @param url
     * @return
     */
    public static Document getHtml(String url, ConstUtil constUtil) {
        Document doc = null;
        try {
            if (constUtil.useProxy) {
                // 设置代理
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
                doc = Jsoup.connect(url)
                        .proxy(proxy)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            } else {
                doc = Jsoup.connect(url)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }
}
